Keywords

let

Characteristics
  • Does not work :

    • x = y = 6  and have both x  and y  have the value 6 .

Typing
  • You cannot change the variable's type.

    let mut spaces = "   ";
    spaces = spaces.len();
    
    • This will cause an error because spaces  attempts to change type from &str  to usize .

Shadowing
  • Shadowing is different from marking a variable as mut  because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let  keyword. By using let , we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.

  • Allowed :

    • Keeps the type:

      let x = 5;
      let x = x + 1;
      
    • Changes the type:

      let spaces = "   ";
      let spaces = spaces.len();
      

const

Differences from let
  • You aren’t allowed to use mut  with constants.

    • Constants aren’t just immutable by default—they’re always immutable.

  • The type of the value must  be annotated.

  • Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of code need to know about.

  • The last difference is that constants may be set only to a constant expression, not the result of a value that could only be computed at runtime.

  • Rust’s naming convention for constants is to use all uppercase with underscores between words.

  • Constants are valid for the entire time a program runs, within the scope in which they were declared.

  • Naming hardcoded values used throughout your program as constants is useful in conveying the meaning of that value to future maintainers of the code. It also helps to have only one place in your code you would need to change if the hardcoded value needed to be updated in the future.